package com.atnjupt.web;

import com.atnjupt.bean.Cart;
import com.atnjupt.bean.User;
import com.atnjupt.service.OrderService;
import com.atnjupt.service.impl.OrderServiceImpl;
import com.atnjupt.utils.JDBCUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Wizarder
 * @create 2021-06-15 10:51
 */
public class OrderSevlet extends BaseServlet{
    private OrderService orderService = new OrderServiceImpl();
    protected void createOrder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取cart对象，和userId
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        User loginUser = (User) request.getSession().getAttribute("user");

        //当用户未登陆，获取不到id，因此跳转登陆页面先登陆，return结束方法
        if (loginUser == null){
            request.getRequestDispatcher("/pages/user/login.jsp").forward(request,response);
            return;
        }

        //调用orderService.createOrder(Cart cart,Integer userId)创建订单并且返回订单
        int id = loginUser.getId();
        String orderId = orderService.createOrder(cart, id);;//在创建订单的同时需要把图书库存减少销量增加
//        request.setAttribute("orderId",orderId);
        //把订单保存到域数据中，再转发到结算页面显示订单,这里用请求重定向，防止刷新重复提交表单
//        request.getRequestDispatcher("/pages/cart/checkout.jsp").forward(request,response);
        request.getSession().setAttribute("orderId",orderId);
        response.sendRedirect(request.getContextPath()+"/pages/cart/checkout.jsp");
    }
}
